import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'

// 添加全局错误处理
window.onerror = function(message, source, lineno, colno, error) {
    console.error('全局错误:', {
        message,
        source,
        lineno,
        colno,
        error
    });
    return false;
};

// 添加Promise错误处理
window.addEventListener('unhandledrejection', function(event) {
    console.error('未处理的Promise错误:', event.reason);
});

// 添加错误边界
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, errorInfo: null };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true };
    }

    componentDidCatch(error, errorInfo) {
        console.error('React组件错误:', {
            error: error,
            errorInfo: errorInfo
        });
        this.setState({
            errorInfo: errorInfo
        });
    }

    render() {
        if (this.state.hasError) {
            return (
                <div style={{
                    padding: '20px',
                    textAlign: 'center',
                    fontFamily: 'Arial, sans-serif'
                }}>
                    <h2>应用加载出错</h2>
                    <p>错误详情：{this.state.errorInfo && this.state.errorInfo.componentStack}</p>
                    <button onClick={() => window.location.reload()}>
                        刷新页面
                    </button>
                </div>
            );
        }
        return this.props.children;
    }
}

// 初始化检查
console.log('开始初始化应用...');

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM已加载完成');
    const root = document.getElementById('root')
    if (root) {
        console.log('找到root元素，开始渲染React应用');
        try {
            ReactDOM.createRoot(root).render(
                <React.StrictMode>
                    <ErrorBoundary>
                        <App />
                    </ErrorBoundary>
                </React.StrictMode>
            )
            console.log('React应用渲染完成');
        } catch (error) {
            console.error('React渲染错误:', error);
            root.innerHTML = `
                <div style="padding: 20px; text-align: center; font-family: Arial, sans-serif;">
                    <h2>应用加载出错</h2>
                    <p>错误信息: ${error.message}</p>
                    <button onclick="window.location.reload()">刷新页面</button>
                </div>
            `;
        }
    } else {
        console.error('未找到root元素');
    }
}) 